<?php

namespace App\Http\Controllers\Guard\Rbac;

use App\Http\Controllers\Common\GuardController;
use App\Models\Rbac\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PermissionController extends GuardController {

    public function lst(Request $request) {
        $permission = new Permission();
        $conditions = ['pid'=>0];
        $conditions['orderBy']['col'] = 'id';
        $conditions['orderBy']['sort'] = 'asc';
        $records = $permission->getLst($conditions)
            //->whereNotIn('id',[1,25,38])
            ->with('children')->get();


        return responseSuccess($records->toArray(),$records->count());
    }

    public function add(Request $request) {
        try{
            $id = $request->input('id',0);
            $name = $request->input('name');
            $path = $request->input('path');
            $title = $request->input('title');
            $pid = $request->input('pid');
            $sort = $request->input('sort',0);
            $icon = $request->input('icon');
            if(empty($icon))$icon = 'table';
            $redirect = $request->input('redirect');
            $is_show = $request->input('is_show',1);
            $component = $request->input('component');
            /*if(!Str::startsWith($component, "/")){
                $component = '/'.$component;
            }*/
            $info = compact('name','path','pid','component','sort','icon','title','redirect','is_show');
            $record = Permission::updateOrCreate(['id'=>$id],$info);

            return responseSuccess($record->toArray());
        }catch(\Exception $e){
            $msg = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($msg);
        }
    }

    public function del(Request $request) {
        return $this->delRecords(Permission::class, $request->input('id',''));
    }

    public function getRecord(Request $request) {

        return $this->getRecordByIds(Permission::class, $request->input('id','')); // TODO: Change the autogenerated stub
    }

}
